<template>
    <el-card style="height:790px" class="nav_card">
        <div slot="header" style="font-weight:bold;font-size:15px;" >
            {{ruleInfo.config_id}} - {{ruleInfo.config_type == 0 ? '列表页' : '详情页'}} - {{ruleInfo.desc}}
        </div>
        <el-form ref="ruleConfForm" label-position="left" label-width="120px" style="height: 710px;overflow-y: scroll" v-loading="formLoading" element-loading-text="数据加载中...">
            <el-form-item label="规则类别">
                <el-select v-model="ruleInfo.config_type" placeholder="请选择规则类别">
                    <el-option label="列表页" :value="0" :key="0"></el-option>
                    <el-option label="详情页" :value="1" :key="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="规则描述" :rules="[{ required: true, message: '规则描述不能为空'}]">
                <el-input v-model="ruleInfo.desc" style="width:75%"></el-input>
            </el-form-item>
            <el-form-item label="url筛选正则">
                <el-input v-model="ruleInfo.url_pattern" :rows="2" style="width:75%"></el-input>
                <span class="alert"><i class="el-icon-info"></i> 若为入口规则则随意</span>
            </el-form-item>
            <el-form-item label="注入操作js">
                <el-tabs type="border-card" @tab-click="queryJs_convert">
                    <el-tab-pane label="预览">
                        <el-button type="primary" icon="el-icon-plus" @click="addQueryJs" size="mini">新增</el-button>
                        <el-table :data="queryJsJSON" style="width: 100%" max-height="350" border fit highlight-current-row>
                            <el-table-column label="#" type="index" width="50px;"></el-table-column>
                            <el-table-column label="操作类型" width="80px;">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.operation_type" size="mini"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作带回的数据" width="140px;">
                                <template slot-scope="scope">
                                    <el-select v-model="scope.row.content_type" placeholder="请选择" size="mini">
                                        <el-option label="无数据" :value="0" :key="0"></el-option>
                                        <el-option label="全文" :value="1" :key="1"></el-option>
                                        <el-option label="执行返回结果" :value="2" :key="2"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="执行完成后等待时间" width="160px;">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.wait" style="width:140px" size="mini"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="该操作执行次数" width="120px;">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.loop" style="width:100px" size="mini" :min="0"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="类型" width="150px;">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.type" type="textarea" :rows="2" size="mini"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="样式选择器" width="150px;">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.css_selector" type="textarea" :rows="2" size="mini"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="js脚本" align="left">
                                <template slot-scope="scope">
                                    <el-popover placement="top" :width="popoverWidth" trigger="click">
                                        <c-codemirror class="jsEditor_textarea" v-model="scope.row.js" :options="jsEditorOptions" ></c-codemirror>
                                        <el-input slot="reference" v-model="scope.row.js" type="textarea" :rows="2" size="mini"></el-input>
                                    </el-popover>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="操作" width="80px;">
                                <template slot-scope="scope">
                                    <el-button type="danger" icon="el-icon-delete" @click.stop="removeQueryJs(scope.$index)" size="mini"></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="源代码">
                        <el-button type="primary" size="mini" @click="queryJs_convert({index: 1})">格式化</el-button>
                        <el-row>
                            <el-col :span="12">
                                <el-input type="textarea" v-model="ruleInfo.query_js" :rows="getRowsFromJsonStr(ruleInfo.query_js)" ></el-input>
                            </el-col>
                            <el-col :span="12">
                                <c-jsonTree :data="queryJsJSON"></c-jsonTree>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>
            <el-form-item label='预注入url'>
                <el-tabs type="border-card" @tab-click="additionUrls_convert">
                    <el-tab-pane label="预览">
                        <el-button type="primary" icon="el-icon-plus" @click="addAdditionUrls" size="mini">新增</el-button>
                        <div v-for="(item, index) in additionUrlsJSON" :key="index">
                            {{index+1}}.&nbsp;&nbsp;<el-input style="width:1200px" size="mini" v-model="item.content"></el-input>
                            <el-button type="danger" icon="el-icon-delete" @click.stop="removeAdditionUrls(index)" size="mini"></el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="源代码">
                        <el-button type="primary" size="mini" @click="additionUrls_convert({index: 1})">格式化</el-button>
                        <el-row>
                            <el-col :span="12">
                                <el-input type="textarea" v-model="ruleInfo.addition_urls" :rows="getRowsFromJsonStr(ruleInfo.addition_urls)" ></el-input>
                            </el-col>
                            <el-col :span="12">
                                <c-jsonTree :data="formatJsonData(ruleInfo.addition_urls)"></c-jsonTree>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>
            <el-form-item label="配置详情">
                <span class="alert"><i class="el-icon-info"></i> 预注入url已有的情况下，该项可为空</span>
                <el-tabs type="border-card" @tab-click="configDetails_convert">
                    <el-tab-pane label="预览">
                        <el-form label-position="left" label-width="100px" inline>
                            <el-form-item label="用来限定block抽取范围的css选择器" label-width="250px">
                                <el-input v-model="configDetailsJSON.limit_pattern" style="width:1100px;" size="mini" type="textarea" :rows="1"></el-input>
                            </el-form-item>
                            <el-form-item label="第几个样式(0-全部)" label-width="250px">
                                <el-input v-model="configDetailsJSON.index" style="width:100px" size="mini" ></el-input>
                            </el-form-item>
                        </el-form>
                        <el-button type="primary" icon="el-icon-plus" @click="addBlock" size="mini">新增block</el-button>
                        <!--v-loading="formLoading" element-loading-text="数据加载中..."-->
                        <el-tabs closable @tab-remove="removeBlock" @tab-click="blockTabClick" type="card">
                            <el-tab-pane v-for="(block, blockIndex) in configDetailsJSON.block" :key="blockIndex" :label="`block${blockIndex+1}`" :name="blockIndex+''">
                                <el-form label-position="left" label-width="100px" inline>
                                    <el-form-item label="选择器类别" label-width="120px">
                                        <el-select v-model="block.pattern_type" placeholder="请选择" size="mini" style="width:100px">
                                            <el-option label="css" value="1" key="1"></el-option>
                                            <el-option label="正则" value="2" key="2"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="第几个样式(0-全部)" label-width="150px">
                                        <el-input v-model="block.index" style="width:100px" size="mini" ></el-input>
                                    </el-form-item>
                                    <el-form-item label="是否去重" label-width="70px">
                                        <el-select v-model="block.dereplication" placeholder="请选择" size="mini" style="width:90px">
                                            <el-option label="不去重" value="0" key="0"></el-option>
                                            <el-option label="去重" value="1" key="1"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="去重依据(字段名)" label-width="120px">
                                        <el-input v-model="block.unique_key" style="width:150px" size="mini"></el-input>
                                    </el-form-item>
                                    <el-form-item label="刷新次数" label-width="70px">
                                        <el-input-number v-model="block.refreshTime" style="width:150px" size="mini" :min="0"></el-input-number>
                                    </el-form-item>
                                    <el-form-item label="落地数据模型" label-width="120px">
                                        <el-select v-model="block.storage_model" style="width:365px;" placeholder="请选择" filterable size="mini">
                                            <el-option label="-不填-" :value="0" :key="0" ></el-option>
                                            <el-option v-for="item in storageModelList" :label="`${item.model_id}--${item.desc}`" :value="item.model_id" :key="item.model_id" >
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="落地数据crawler_status的初始值" label-width="220px">
                                        <el-input v-model="block.storage_status" style="width:50px" size="mini"></el-input>
                                    </el-form-item>
                                    <el-form-item label="选择器内容" label-width="120px">
                                        <el-input v-model="block.pattern" style="width:1300px" size="mini" type="textarea" :rows="1"></el-input>
                                    </el-form-item>
                                    <el-form-item label="注入js脚本" label-width="120px" align="left">
                                        <el-popover placement="top" :width="popoverWidth" trigger="click">
                                            <c-codemirror class="jsEditor_textarea" v-model="block.include_js" :options="jsEditorOptions"></c-codemirror>
                                            <el-input slot="reference" v-model="block.include_js" style="width:1280px" size="mini" type="textarea" :row="2"></el-input>
                                        </el-popover>
                                        <br>
                                        <span class="alert">
                                            <i class="el-icon-info"></i>&nbsp;可用变量有-->&nbsp;&nbsp;&nbsp;&nbsp;
                                            linkDataTemp : 抽取到的一个有效数据obj(key字段名，value字段值) &nbsp;&nbsp;&nbsp;&nbsp;
                                            xml2JsonObj() : xml解析为Json &nbsp;&nbsp;&nbsp;&nbsp;
                                            common.make_md5_string() : 生成md5
                                        </span>
                                    </el-form-item>
                                </el-form>
                                <!--新增字段-->
                                <label style="color:#F07F1F">需要抓取的字段列表({{block.details ? block.details.length : 0}})： </label>
                                <el-button type="primary" icon="el-icon-plus" @click="addField(blockIndex)" size="mini">新增字段</el-button>
                                <el-button type="primary" @click="autoCreateFields(blockIndex, Number(block.storage_model))" size="mini">根据数据模型一键生成字段</el-button>
                                <el-table :data="block.details" style="width: 100%" max-height="565" border fit highlight-current-row>
                                    <el-table-column label="#" type="index" width="50px;"></el-table-column>
                                    <el-table-column align="center" label="过滤" width="100px;">
                                        <el-table-column align="center" label="个数" width="50px;">
                                            <template slot-scope="scope">
                                                {{scope.row.filter_pattern_list ? scope.row.filter_pattern_list.length : 0}}
                                            </template>
                                        </el-table-column>
                                        <el-table-column align="center" type="expand" label="展开" width="50px;">
                                            <template slot-scope="scope">
                                                <el-button type="primary" icon="el-icon-plus" @click="addFilterPatternList(blockIndex, scope.$index);" size="mini" title="新增选择器">新增过滤</el-button>
                                                <el-table :data="scope.row.filter_pattern_list" style="width: 100%" max-height="230" border fit highlight-current-row>
                                                    <el-table-column label="#" type="index" width="50px;"></el-table-column>
                                                    <el-table-column label="选择器类别" width="100px;">
                                                        <template slot-scope="scope_filter">
                                                            <el-select v-model="scope_filter.row.filter_type" placeholder="请选择" size="mini">
                                                                <el-option label="css" value="1" key="1"></el-option>
                                                                <el-option label="正则" value="2" key="2"></el-option>
                                                            </el-select>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column label="选择器内容">
                                                        <template slot-scope="scope_filter">
                                                            <el-input v-model="scope_filter.row.filter_pattern" size="mini" type="textarea" :rows="1"></el-input>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column label="操作" width="80px;" align="center">
                                                        <template slot-scope="scope_filter">
                                                            <el-button type="danger" icon="el-icon-delete" @click.stop="removeFilter(blockIndex, scope.$index, scope_filter.$index)" size="mini"></el-button>
                                                        </template>
                                                    </el-table-column>
                                                </el-table>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>
                                    <el-table-column label="字段名称" width="180px;">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.fieldName" size="mini"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="选择器类别" width="100px;" align="center">
                                        <template slot-scope="scope">
                                            <el-select v-model="scope.row.pattern_type" placeholder="请选择" size="mini">
                                                <el-option label="css" value="1" key="1"></el-option>
                                                <el-option label="正则" value="2" key="2"></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="第几个样式(0-全部)" width="90px;" align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.index" size="mini" ></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="文本类别" width="140px;" align="center">
                                        <template slot-scope="scope">
                                            <el-select v-model="scope.row.content_type" placeholder="请选择" size="mini">
                                                <el-option label="html" value="0" key="0"></el-option>
                                                <el-option label="text" value="1" key="1"></el-option>
                                                <el-option label="时间类型" value="2" key="2"></el-option>
                                                <!--<el-option label="时间类型(ms)" value="3" key="3"></el-option>-->
                                                <el-option label="url" value="4" key="4"></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="选择器内容" width="350px;" align="left">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.pattern" size="mini" type="textarea" :row="2"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="注入js脚本" align="left">
                                        <template slot-scope="scope">
                                            <el-popover placement="left" :width="popoverWidth" trigger="click">
                                                <c-codemirror class="jsEditor_textarea" v-model="scope.row.include_js" :options="jsEditorOptions" ></c-codemirror>
                                                <el-input slot="reference" v-model="scope.row.include_js" size="mini" type="textarea" :row="2"></el-input>
                                            </el-popover>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="70px" align="center">
                                        <template slot-scope="scope">
                                            <el-button type="danger" icon="el-icon-delete" @click="removeField(blockIndex, scope.$index)" size="mini"></el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>

                            </el-tab-pane>
                        </el-tabs>
                    </el-tab-pane>
                    <el-tab-pane label="源代码">
                        <el-button type="primary" size="mini" @click="configDetails_convert({index: 1})">格式化</el-button>
                        <el-row>
                            <el-col :span="12">
                                <el-input type="textarea" v-model="ruleInfo.config_details" :rows="getRowsFromJsonStr(ruleInfo.config_details)"></el-input>
                            </el-col>
                            <el-col :span="12">
                                <c-jsonTree :data="configDetailsJSON"></c-jsonTree>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>
            
            <el-form-item label="编码">
                <el-select v-model="ruleInfo.encoding" placeholder="请选择" style="width:150px" >
                    <el-option label="utf8" value="utf8" key="utf8"></el-option>
                    <el-option label="gbk" value="gbk" key="gbk"></el-option>
                    <el-option label="gb2313" value="gb2313" key="gb2313"></el-option>
                    <el-option label="ascii" value="ascii" key="ascii"></el-option>
                    <el-option label="unicode" value="unicode" key="unicode"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="自定义ua">
                <el-input v-model="ruleInfo.useragent" style="width:75%"></el-input>
            </el-form-item>
            <el-form-item label="自定义cookie">
                <el-input v-model="ruleInfo.cookie" style="width:75%"></el-input>
            </el-form-item>
            <el-form-item label="是否加载图片">
                <el-switch v-model="ruleInfo.load_image" :active-value = "1" :inactive-value = "0"></el-switch>
                <span class="alert"><i class="el-icon-info"></i> 不保留图片的情况下会清理掉img标签</span>
            </el-form-item>
            <el-form-item label="图片css选择器">
                <el-input type="textarea" :rows="1" v-model="ruleInfo.image_pattern" style="width:75%"></el-input>
            </el-form-item>
            <el-form-item label="是否模拟浏览">
                <el-switch v-model="ruleInfo.phantomJs" :active-value = "1" :inactive-value = "0"></el-switch>
            </el-form-item>
            <el-form-item label="是否使用代理">
                <el-switch v-model="ruleInfo.use_proxy" :active-value = "1" :inactive-value = "0"></el-switch>
            </el-form-item>
            <el-form-item label="是否是附件">
                <el-switch v-model="ruleInfo.is_attach" :active-value = "1" :inactive-value = "0"></el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="submitLoading" :loading="submitLoading" @click="submitForm">保存</el-button>
                <!--<el-button>取消</el-button>-->
            </el-form-item>
        </el-form>
    </el-card>
</template>
<script>
import { getRuleInfoById, saveRuleInfo, getStorageModelList } from '../../api/crawl.js';
import JsonTree from 'vue-json-tree';
import lodash from 'lodash';
import icon from 'vue-awesome';
//import stringifyObject from 'stringify-object';
import stringifyObject from 'json-stringify-pretty-compact';//将json格式化
import { codemirror } from 'vue-codemirror-lite';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/display/autorefresh';
//import 'codemirror/addon/lint/lint'
//import 'codemirror/addon/lint/javascript-lint'
//import 'codemirror/addon/lint/lint.css'

//require("codemirror/mode/htmlembedded/htmlembedded");
export default {
    components: { 
        'c-jsonTree' : JsonTree,
        'c-codemirror' : codemirror,
        'c-icon' : icon,
    },
    data(){
        return {
            popoverWidth : 800,//代码编辑器的宽度
            formLoading : false,
            submitLoading : false,
            jsEditorOptions : {
                mode : 'text/javascript',
                tabSize : 4,
                lineNumbers : true,
                scrollbarStyle : null,
                scrolled : false,
                autoRefresh : true,
                //lint: true,
                //gutters: ['CodeMirror-lint-markers'],
                //fixedGutter : false,
                //theme: 'monokai',
                //autofocus : true,
                //viewportMargin: Infinity,
                //flattenSpans: false,//默认情况下，CodeMirror会将使用相同class的两个span合并成一个。通过设置此项为false禁用此功能。
                //lineWrapping : 'wrap',
                //showCursorWhenSelecting : true,//在选择时是否显示光标，默认为false。
            },
            ruleConfForm : {
            },
            ruleInfo : {
                config_id : 0,
                config_type : 0,
                desc : '',
                url_pattern : '',
                query_js : '',
                config_details : '',
                addition_urls : '',
                encoding : 'utf8',
                useragent : '',
                cookie : '',
                load_image : 1,
                image_pattern : 'img',
                phantomJs : 0,
                use_proxy : 0,
                is_attach : 0,
            },
            detailsList : [], //configDetailsJSON.block.details
            //配置详情JSON
            configDetailsJSON :{
                limit_pattern:'',
                index:'1',
                block: [
                    {
                        pattern_type: '1',
                        pattern: '',
                        index: 0,
                        dereplication: '1',
                        refreshTime: '0',
                        unique_key: 'link',
                        storage_model: 0,
                        storage_status: '',
                        include_js: '',
                        details: [],
                    }
                ]
            },
            //注入操作JS
            queryJsJSON : [],
            //预注入url
            additionUrlsJSON : [],
            storageModelList : [], //模型列表
            //一键生成字段时，如果模型id>=0 && <=10，不生成如下字段
            exFieldNames : ['news_id','station_id','crawl_time','crawl_status','attach_status','crawler_route','refresh_count','extra','list_img_url','attach_num','is_has_attach','machine_no','news_content_text','cope_time']
        }
    },
    created(){
        this.initStorageModelList();
        const config_id = this.$route.params.config_id;
        if(Number(config_id)){
            this.ruleInfo.config_id = config_id;
            this.initRuleInfoById();
        }else{
            this.ruleInfo.config_id = 0;
        }
    },
    watch: {
        'ruleInfo.config_details': function(val, oldVal){
            if(val != oldVal){
                this.configDetails_convert({index : 0});
            }
         },
         'ruleInfo.query_js': function(val, oldVal){
            if(val != oldVal){
                this.queryJs_convert({index : 0});
            }
         },
         'ruleInfo.addition_urls': function(val, oldVal){
            if(val != oldVal){
                this.additionUrls_convert({index : 0});
            }
         }
    },
    methods: {
        initRuleInfoById(){
            this.formLoading = true;
            getRuleInfoById(this.ruleInfo.config_id).then(data=>{
                console.log('getRuleInfoById------------',data);
                this.ruleInfo = data.rows[0];
                this.formLoading = false;
            })
        },
        initStorageModelList(){
            getStorageModelList().then(data=>{
                this.storageModelList = data.rows;
            })
        },
        //去掉json字符串中的缩进和换行，转为json对象
        formatJsonData(str){
            let obj = {};
            if(str){
                let jsonStr = str.replace(/(\r\n)|(\n)/g, '').replace(/(\")/g,'"');
                try{
                    obj = JSON.parse(jsonStr);
                }catch(e){
                    console.log(e)
                }
            }
            return obj;
        },
        /*把json对象转为字符串，并增加换行和制表符
        formatJsonObj(jsonObj){
            let str = '';
            if(jsonObj){
                str = JSON.stringify(jsonObj);
                str = str.replace(/{/g, '{\n').replace(/}/g, '}\n').replace(/\[/g, '[\n').replace(/\]/g, ']\n');
                try{
                    obj = JSON.parse(jsonStr);
                }catch(e){
                    console.log(e)
                }
            }
            return str;
        },
        */
        //根据json字符串中换行符的个数得到文本域的行数
        getRowsFromJsonStr(str){
            let rows = 2;
            if(str){
                let result = str.match(new RegExp('\n',"g"));//返回所有匹配的字符串的数组
                rows = result == null ? rows : result.length + 3;//+5是为了跟jsontree容器平齐
            }
            return rows;
        },
        //切换配置详情的预览和源代码时json对象和json源代码互转
        configDetails_convert(tabObj){
            const tabIndex = Number(tabObj.index);
            console.log('configDetails_convert------------', tabIndex);
            this.formLoading = true;
            if(tabIndex === 0){//预览 - json字符串转json对象
                if(this.ruleInfo && this.ruleInfo.config_details){
                    this.configDetailsJSON = this.formatJsonData(this.ruleInfo.config_details);
                    //把configDetailsJSON.block.details 从map转为list
                    if(this.configDetailsJSON.block){
                        for(let index in this.configDetailsJSON.block){
                            let block = this.configDetailsJSON.block[index];
                            if(block.details){
                                let detailsObj = block.details;
                                let detailsList = [];
                                for(let fieldName in detailsObj){
                                    let field = detailsObj[fieldName];
                                    field.fieldName = fieldName;
                                    detailsList.push(field);
                                }
                                this.configDetailsJSON.block[index].details = detailsList;
                            }
                        }
                    }
                }
            }else if(tabIndex === 1){//源代码
                //把configDetailsJSON.block.details 从list转为map
                if(this.configDetailsJSON.block){
                    let configDetailsJSON = JSON.parse(JSON.stringify(this.configDetailsJSON));//避免原对象被修改
                    try{
                        for(let i = 0; i < configDetailsJSON.block.length; i++){
                            let detailsList = configDetailsJSON.block[i].details;
                            if(detailsList.length){
                                let detailsObj = {};
                                for(let j = 0; j < detailsList.length; j++){
                                    let field = detailsList[j];
                                    let fieldName = field.fieldName;
                                    if(fieldName.trim()){
                                        if(detailsObj[fieldName]){
                                            this.$notify({
                                                title: '提示',
                                                message: `block${i+1}有重复的字段名[${fieldName}]（已重命名），请检查！`,
                                                duration: 0
                                            });
                                            fieldName = fieldName + (new Date().getTime());
                                        }
                                        detailsObj[fieldName] = field;
                                    }
                                }
                                for(let fieldName in detailsObj){
                                    detailsObj[fieldName] = lodash.omit(detailsObj[fieldName], ['fieldName']);//移除fieldName属性
                                }
                                configDetailsJSON.block[i].details = detailsObj;
                            }
                        }

                        this.ruleInfo.config_details = stringifyObject(configDetailsJSON, {
                            //indent: '\t'
                            /*
                            singleQuotes: false,
                            transform: (obj, prop, originalResult) => {
                                if (prop === 'pattern') {
                                    return originalResult.replace(/"/g, '\"');
                                } else {
                                    return originalResult;
                                }
                            }
                            */
                        });
                    }catch(e){
                        console.error(e);
                    }
                }
            }
            this.formLoading = false;
        },
        //新增block
        addBlock(){
            if(!this.configDetailsJSON.block){
                this.configDetailsJSON.block = [];
            }
            this.configDetailsJSON.block.push({
                pattern_type: '1',
                pattern: '',
                index: 0,
                dereplication: '1',
                refreshTime: '0',
                unique_key: 'link',
                storage_model: 0,
                storage_status: '',
                include_js: '',
                details: []
            });
        },
        //删除block
        removeBlock(tabName){
            const tabIndex = Number(tabName);
            this.$confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.configDetailsJSON.block.splice(tabIndex, 1);//tabName就是数组索引
            }).catch(() => {
            });
        },
        //新增字段
        addField(blockIndex){
            if(!this.configDetailsJSON.block[blockIndex].details){
                this.configDetailsJSON.block[blockIndex].details = [];
            }
            this.configDetailsJSON.block[blockIndex].details.push({
                fieldName : '',
                pattern_type: '1',
                pattern: '',
                index: '1',
                content_type: '1',
                include_js: '',
                filter_type: '',
                filter_pattern_list: []
            });
        },
        //根据模型ID一键生成字段
        autoCreateFields(blockIndex, model_id){
            if(model_id){
                let storageModelList = this.storageModelList.filter(item => item.model_id === Number(model_id));//查找指定模型id下的模型对象
                if(storageModelList.length && storageModelList[0].sequelize_details){
                    let sequelizeDetails = JSON.parse(storageModelList[0].sequelize_details);//指定模型id下的所有字段名
                    for(let fieldName in sequelizeDetails){
                        let isContinue = true;
                        if(Number(model_id)>=0 && Number(model_id)<=10){//在此区间内的模型，有一部分字段名不需要生成
                            if(this.exFieldNames.includes(fieldName)){
                                isContinue = false; 
                            }
                        }
                        if(isContinue){
                            let result = lodash.find(this.configDetailsJSON.block[blockIndex].details, { 'fieldName': fieldName });//查找列表中是否已经存在该字段
                            if(!result){
                                this.configDetailsJSON.block[blockIndex].details.push({
                                    fieldName,
                                    pattern_type: '1',
                                    pattern: '',
                                    index: '1',
                                    content_type: '1',
                                    include_js: '',
                                    filter_type: '',
                                    filter_pattern_list: []
                                });
                            }
                        }
                    }
                    this.$message({
                        message: '生成成功！',
                        type: 'success'
                    });
                }else{
                    this.$message({
                        message: `模型${model_id}下暂无字段`,
                        type: 'danger'
                    });
                }
            }else{
                this.$message({
                    message: `请先选择落地数据模型！`,
                    type: 'danger'
                });
            }
        },
        //删除字段
        removeField(blockIndex, detailIndex){
            this.$confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.configDetailsJSON.block[blockIndex].details.splice(detailIndex, 1);
            }).catch(() => {

            });
        },
        //新增字段下的过滤选择器
        addFilterPatternList(blockIndex, detailIndex){
            this.configDetailsJSON.block[blockIndex].details[detailIndex].filter_pattern_list.push(
                {
                    filter_type: '1',
                    filter_pattern: ''
                }
            )
        },
        //移除字段下的过滤选择器
        removeFilter(blockIndex, detailIndex, filterIndex){
            this.$confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.configDetailsJSON.block[blockIndex].details[detailIndex].filter_pattern_list.splice(filterIndex, 1);
            }).catch(() => {

            });
        },
        //增加注入操作js行
        addQueryJs(){
            this.queryJsJSON.push({
                operation_type: 3,
                content_type: 1,
                js: '',
                wait: 1000,
                loop: 1,
                type: '',
                css_selector: '',
            })
        },
        //移除注入操作js行
        removeQueryJs(index){
            this.$confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.queryJsJSON.splice(index, 1);
            }).catch(() => {

            });
        },
        //切换注入操作js的tab时json对象和json源代码互转
        queryJs_convert(tabObj){
            const tabIndex = Number(tabObj.index);
            if(tabIndex === 0){//预览 - json字符串转json对象
                if(this.ruleInfo && this.ruleInfo.query_js){
                    this.queryJsJSON = this.ruleInfo.query_js ? this.formatJsonData(this.ruleInfo.query_js) : [];
                }
            }else if(tabIndex === 1){//源代码 - json对象转json字符串
                this.ruleInfo.query_js = stringifyObject(this.queryJsJSON, {
                    //indent: '\t'
                });
            }
        },
        //增加预注入url
        addAdditionUrls(){
            this.additionUrlsJSON.push({
                content : ''
            });
        },
        //移除预注入url
        removeAdditionUrls(index){
            this.$confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.additionUrlsJSON.splice(index, 1);
            }).catch(() => {

            });
        },
        //切换预注入url的tab时json对象和json源代码互转
        additionUrls_convert(tabObj){
            const tabIndex = Number(tabObj.index);
            if(tabIndex === 0){//预览 - json字符串转json对象
                if(this.ruleInfo && this.ruleInfo.addition_urls){
                    let additionUrlsJSON = [];//转成正确的格式
                    let additionUrlsJSONTmp = this.formatJsonData(this.ruleInfo.addition_urls);
                    if(additionUrlsJSONTmp && additionUrlsJSONTmp.urlList){
                        additionUrlsJSONTmp.urlList.forEach(url=>{
                            additionUrlsJSON.push({ content : url });
                        });
                    }
                    this.additionUrlsJSON = additionUrlsJSON;
                }
            }else if(tabIndex === 1){//源代码 - json对象转json字符串
                let additionUrlsJSON = { urlList: [] };//转成正确的格式
                if(this.additionUrlsJSON && this.additionUrlsJSON.length){
                    this.additionUrlsJSON.forEach(item=>{
                        additionUrlsJSON.urlList.push(item.content);
                    })
                }
                this.ruleInfo.addition_urls = stringifyObject(additionUrlsJSON, {
                    //indent: '\t'
                });
            }
        },
        //保存
        async submitForm(){
            //把三个json字段的json对象转为json字符串
            this.configDetails_convert({index : 1});
            this.additionUrls_convert({index : 1});
            this.queryJs_convert({index : 1});
            const postData = Object.assign({}, this.ruleInfo);
            this.submitLoading = true;
            const res = await saveRuleInfo(postData);
            this.submitLoading = false;
            console.log('saveRuleInfo------',res)
            if(res){
                if (res.config_id) {
                    this.$alert('新增成功！', '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                            this.$router.push('/ruleList');
                        }
                    });
                }else if (res === 1) {
                    this.$confirm('修改成功！', '提示', {
                        confirmButtonText: '返回列表页',
                        cancelButtonText: '留在本页',
                        type: 'warning'
                    }).then(() => {
                        this.$router.push('/ruleList');
                    }).catch((e) => {
                        //console.error(e);
                    });
                }
            }else{
                this.$message({
                    message: '保存失败！',
                    type: 'danger'
                });
            }
        },
        //block的选项卡被选中时
        blockTabClick(tabObj){
            const tabIndex = Number(tabObj.index);
            //console.log('tabIndex----',tabIndex)
            //this.configDetailsJSON.block[tabIndex - 1].include_js = '11111111111111';
            //this.$set(this.configDetailsJSON.block, 'children', []);
            //this.$set(this.items, item.index, item);
        }
    }
};
</script>